#!/usr/bin/python
#-*- coding:utf-8 -*-

# clatividades.py
#
# Copyright (c) 2007 Marcelo Lira dos Santos
#
# Author: Marcelo Lira dos Santos <setanta@gmail.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA

import pygtk
pygtk.require('2.0')
import gtk
import gtk.glade

import os
from activity import *
from activity_window import ActivityWindow

# Global vars
USERPATH = os.path.expanduser('~')

if os.environ.has_key('DEVEL') and os.environ['DEVEL'] == '1':
    DATAPATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                            '..', 'data')
    ICONPATH = os.path.join(DATAPATH, 'icons')
    ICONFILE = os.path.join(ICONPATH, 'board.png')
else:
    DATAPATH = os.path.join('@PREFIX@', 'share', 'clatividades')
    ICONPATH = os.path.join('@PREFIX@', 'share', 'pixmaps')
    ICONFILE = os.path.join(ICONPATH, 'board.png')

DBFILE = os.path.join(DATAPATH, 'clatividades.db')
GLADEFILE = os.path.join(DATAPATH, 'clatividades.glade')

class AtividadesApp:

    (
    ACTIVITY_ID,
    ACTIVITY_TITLE,
    ACTIVITY_DESCRIPTION,
    ACTIVITY_PROGRAM,
    ACTIVITY_CATEGORY,
    ACTIVITY_OBJECT
    ) = range(6)

    def __init__(self):
        self.repo = ActivityDB(DBFILE)
        self.categories_icons = {}
        self.search_result = []

        self.wtree = gtk.glade.XML(GLADEFILE)

        #Widgets -------
        #Get the Main Window, and connect the 'destroy' event
        self.window = self.wtree.get_widget('cienciaLivre')
        self.window.set_icon_from_file(ICONFILE)
        self.window.connect('destroy', gtk.main_quit)


        self.search_entry = self.wtree.get_widget('searchEntry')

        #Categories TreeView
        self.categories_view = self.wtree.get_widget('categoriesView')
        self.categories_view_store = gtk.ListStore(int, gtk.gdk.Pixbuf, str)
        self.categories_view.set_model(self.categories_view_store)
        column = gtk.TreeViewColumn('', gtk.CellRendererPixbuf(), pixbuf=1)
        self.categories_view.append_column(column)
        column = gtk.TreeViewColumn('', gtk.CellRendererText(), text=2)
        self.categories_view.append_column(column)

        self.search_entry = self.wtree.get_widget('searchEntry')

        #Activities TreeView & Filter
        self.activities_view = self.wtree.get_widget('activitiesView')
        self.activities_view_store = gtk.ListStore(int, str, str, str, int, Activity)
        column = gtk.TreeViewColumn('Atividade', gtk.CellRendererText(), text=1)
        self.activities_view.append_column(column)
        self.activities_filter = self.activities_view_store.filter_new()
        self.activities_view.set_model(self.activities_filter)
        self.activities_filter.set_visible_func(self.activities_visible, data=None)

        #Description TextView, TextBuffer & Tags
        self.activity_desc = self.wtree.get_widget('activityDescription')
        self.activity_desc_buffer = gtk.TextBuffer()
        title_tag = gtk.TextTag('title')
        title_tag.set_property('pixels-below-lines', 4)
        title_tag.set_property('font', 'sans bold 12')
        tag_table = self.activity_desc_buffer.get_tag_table()
        tag_table.add(title_tag)
        self.activity_desc.set_buffer(self.activity_desc_buffer)

        self.fill_categ_list()
        self.fill_activity_list()

        #Autoconnect Signals and Callbacks
        self.wtree.signal_autoconnect(self)

        self.window.show_all()

    # Callbacks ---------------------------------------------------------------
    def categoriesView_cursor_changed_cb(self, widget):
        index = widget.get_cursor()[0]
        self.activities_filter.refilter()
        self.clear_activity_desc()

    def activitiesView_cursor_changed_cb(self, widget):
        index = widget.get_cursor()[0]
        self.show_activity_desc(self.activities_filter[index][1],
                self.activities_filter[index][2])

    def searchBtn_clicked_cb(self, widget):
        wordset = set(self.search_entry.get_text().split(' '))
        wordset.discard('')
        self.search(wordset)

    def showActivity_clicked_cb(self, widget):
        self.show_activity()

    def activitiesView_row_activated_cb(self, widget, param1, param2):
        self.show_activity()

    # Auxiliary Methods -------------------------------------------------------
    def fill_categ_list(self):
        self.categories_icons[-1] = gtk.gdk.pixbuf_new_from_file(\
                os.path.join(ICONPATH, 'all.png'))
        self.categories_view_store.append(
                [-1, self.categories_icons[-1], 'Todos']
        )
        for item in self.repo.get_all_categories():
            self.categories_icons[item[0]] = gtk.gdk.pixbuf_new_from_file(\
                    os.path.join(ICONPATH, item[2]))
            self.categories_view_store.append(\
                [item[0], self.categories_icons[item[0]], item[1]]
            )

        self.categories_view.set_cursor(0)

    def fill_activity_list(self):
        for ac in self.repo.get_all_activities():
            row = [ac.id, ac.title, ac.description, ac.program, ac.category, ac]
            self.activities_view_store.append(row)

    def clear_activity_desc(self):
        self.activity_desc_buffer.set_text('')

    def show_activity_desc(self, title, description):
        self.activity_desc_buffer.set_text('')
        sob, eob = self.activity_desc_buffer.get_bounds()
        self.activity_desc_buffer.\
                insert_with_tags_by_name(eob, title, 'title')
        self.activity_desc_buffer.insert_at_cursor('\n' + description)

    def show_activity(self):
        index = self.activities_view.get_cursor()[0]
        activity = self.activities_filter[index][AtividadesApp.ACTIVITY_OBJECT]
        ac_window = ActivityWindow(GLADEFILE, activity)
        try:
            icon = self.categories_icons[activity.category];
        except:
            icon = self.categories_icons[-1];
        ac_window.set_icon(icon);
        #os.popen4(self.activities_filter[index][AtividadesApp.ACTIVITY_PROGRAM])

    def activities_visible(self, model, iter, user_data):
        index = self.categories_view.get_cursor()[0]
        categ_id = self.categories_view_store[index][AtividadesApp.ACTIVITY_ID]

        if categ_id == -1:
            result = True
        else:
            result = (model.get_value(iter, AtividadesApp.ACTIVITY_CATEGORY) \
                      == categ_id)

        if self.search_result:
            result = result and \
                model.get_value(iter, AtividadesApp.ACTIVITY_ID) in \
                        self.search_result

        return result

    def search(self, wordset):
        if not wordset:
            return
        self.search_result = self.repo.search(wordset)
        self.activities_filter.refilter()
        self.clear_activity_desc()

    def run(self):
        gtk.main()


def main():
    app = AtividadesApp()
    app.run()

if __name__ == '__main__':
    main()

